package com.debai.controller;

import com.debai.pojo.Admin;
import com.debai.pojo.Position;
import com.debai.pojo.User;
import com.debai.service.PositionService;
import com.debai.service.UserService;
import com.debai.util.JwtUtil;
import com.debai.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PositionService positionService;

    //添加用户(json,店铺名字)
    @PostMapping("/insert")
    public Result insert(@RequestBody User user, @RequestParam(name = "positionName") String positionName, @RequestHeader(name = "Authorization") String token) {
        User user1=userService.selectByName(user.getUserName());
        Position position = positionService.selectByName(positionName);
        int positionId = position.getId();

        if (user1==null){
            int i = userService.insert(user, positionId, token);
            if (i == 0) {
                return Result.error("插入失败");
            }
            return Result.success();
        }else {
            return Result.error("用户名已存在");
        }

    }

    //查看已经创建的用户信息
    @GetMapping("/selectAll")
    public Result<List<User>> selectAll() {
        return Result.success(userService.selectAll());
    }

    //根据删除用户
    @DeleteMapping
    public Result delete(int userId) {
        int i = userService.delete(userId);
        if (i == 0) {
            return Result.error("删除失败");
        }
        return Result.success();
    }

    /*
       user用户登录
  */
    @PostMapping("/login")
    public Result login(@RequestParam(name = "userName") String userName, @RequestParam(name = "userPassword") String userPassword) {
        User user = userService.selectByAccountAndPassword(userName, userPassword);
        System.out.println(user);
        //用Map集合进行封装
        Map<String, Object> claims = new HashMap<>();
        if (user != null) {
            claims.put("userId", user.getId());
            claims.put("positionId", user.getPositionId());
            System.out.println(claims.get("positionId"));
            //生成jwt令牌
            String jwt = JwtUtil.genToken(claims);
            System.out.println("登录成功！！！！！");
            return Result.success(jwt);
        } else {
            System.out.println("登录失败！！！");
            return Result.error("用户名或密码错误");
        }
    }


}
